import $store from '@/store/index.js'
import http from '@/common/request'
import fc from '@/common/publicFc'

import uniImStorage from '@/uni_modules/uni-im/common/uni-im-storage.js'
export default class Message {
	constructor(currentConversation) {
		this.currentConversation = currentConversation
		this.conversation_id = this.currentConversation.id
		// this.msgList = this.currentConversation.msgList
		// this.isInit = this.currentConversation.isInit
		Object.defineProperty(this, 'msgList', {
			get() {
				return this.currentConversation.list
			}
		})
		Object.defineProperty(this, 'isInit', {
			get() {
				return this.currentConversation.isInit?this.currentConversation.isInit:false;
			}
		})
	}
	isInit = false
	msgList = []
	pageLimit = uniImStorage.pageLimit
	storage = uniImStorage
	async getMore() {
		const that = this
		let res = {
			data: []
		}
		//未加载过数据，先将storage中的第一页取出然后按最大时间查询此时间之后的数据
		console.error('this.isInit',this.isInit);
		if (this.isInit === false) {
		      var oneTime = Date.now()+1000;
			let {
				data
			} = await this.storageMsg.get('',oneTime)
            console.log('msg1-init',data.length);
			if (data.length) {
			    data = this.format_data(data);
				res.data = [...data];
                return res.data
			}
		}
		// 加载storage中的数据
		if (this.storageMsg.hasMore) {
			//console.error('this.storageMsg.hasMore',this.storageMsg.hasMore)
			// console.log('resresresresres',res);
			let {
				data
			} = await this.storageMsg.get(res)
            console.log('msg3-bendi',data.length);
			if (data.length) {
			    data = this.format_data(data);
				// console.log('2await this.storageMsg.get()', data);
				res.data.push(...data)
				return res.data
			}
		} else {
			// console.error('this.storageMsg.hasMore',this.storageMsg.hasMore)
		}
 
		//加载比storage时间更旧的数据
		if (this.beforeStorageMsg.hasMore) {
			// console.error('this.beforeStorageMsg.hasMore',this.beforeStorageMsg.hasMore)
			let {
				data
			} = await this.beforeStorageMsg.get(res)
            console.log('msg4-old-cloud',data.length);
			if (data.length) {
				// console.log('3await this.beforeStorageMsg.get()', data);
				res.data.push(...data)
				return res.data
			}
		} else {
			// console.error('this.beforeStorageMsg.hasMore',this.beforeStorageMsg.hasMore)
		}
		return res.data
	}
    
	async getAftermsg(msglist) {
		const that = this
		let res = {
			data: []
		}
		// return res.data
		//加载比storage时间更后的数据
		if (this.afterStorageMsg.hasMore) {
			let {data} = await this.afterStorageMsg.get(msglist);
            console.log('msg2-new-cloud',data.length);
            if (data.length) {
				res.data=data;
				return res.data
			}
			// console.log('1await this.afterStorageMsg.get()',data);
		} else {
			 console.error('this.afterStorageMsg.hasMore',this.afterStorageMsg.hasMore)
		}
		return res.data
	}
	async getCloudMsg({
		minTime,
		maxTime,
		limit = 50
	}) {
	   var param ={};
       param.conversation_id=this.conversation_id;
		// console.log('this',this);
		if (minTime) {
            param.minTime=minTime;
		}
		if (maxTime) {
            param.maxTime=maxTime;
		}
		if (limit) {
            param.limit=limit;
		}
        
		/*const db = uniCloud.database();
		const msgTable = db.collection('uni-im-msg')*/
		let data;
        console.log(param);
		if(minTime>0 || maxTime>0){
    		  try{
                var res = await this.getRecord(param);
                if(fc.check_emoji()){
                    data = JSON.parse(JSON.stringify(res));
                }else{
                    for(var i in res){
                        if(res[i].msgType == 'TEXT' && res[i].content)res[i].content = fc.filteremoji(res[i].content);
                    }
                    data=res;
                }
    		}catch(e){
    		//			console.log('error'
    			data = []
    			//TODO handle the exception
    		}
		}else{
		  	data = []
		}
		//存到本地
		uniImStorage.insert([...data], minTime != 0)
		return {
			data
		}
	}
    getRecord(param){
		return new Promise((resolve, reject) => {
            http.request({
    			url: '/chat/record',
    			method: 'POST',
    			data: JSON.stringify(param),
    			success: res => {
    				//console.log(res.data);
    				if (res.data.code == '200') {
                       resolve(res.data.data);                                             					   
    				}
    			}
    		});
		});
    }
    format_data(data){
        var userinfo =$store.state.userInfo;
        if(userinfo && this.conversation_id && this.conversation_id.indexOf('GROUP')>-1){
            var list = fc.getKeyObjectStorage(userinfo.userId+'_'+'GroupNameData');
            if(list){
                for(var i in data){
                    var datakey = data[i].userId+'_'+data[i].personId;
                    if(list[datakey] && list[datakey]!=data[i].nickName){
                        data[i].nickName=list[datakey];
                    }
                }
            }
            //console.log(list);
        }
        return data;
    }
	async getStorageMsg(e = {}) {
		let res = uniImStorage.getData({
			conversation_id: (e.conversationId || this.conversation_id),
			page: e.page || 0,
			maxTime: e.maxTime
		})
		return {
			data: res,
			hasMore: 0
		}
	}
	storageMsg = {
		get: async (e,m) => {
			let maxTime;
			let data = this.msgList
			if(data.length == 0 && e){
				data = e.data
			}
            if(m && m>0){
                maxTime = m;
            }else{
                if(data.length){
    			    maxTime = this.getmintime(data);
    			}else{
    			    maxTime = Date.now()+1000;
    			}
            }
			
			console.log('maxTime',maxTime);
			let res = await this.getStorageMsg({
				maxTime
			});
			this.storageMsg.hasMore = res.data.length != 0
			return res
		},
		hasMore: true,
		maxTime: false
	}
	afterStorageMsg = {
		//时间大于storage中最大时间的服务端数据
		get: async (msglist) => {
		    if(!msglist)msglist =  this.msgList;
			if (msglist && msglist.length>0) {
			    var where = {};
				where.minTime = this.getmaxtime(msglist);
                where.limit = 50;
                let res = await this.getCloudMsg(where)
    			const dataLength = res.data.length;
    			this.afterStorageMsg.hasMore = dataLength==where.limit;
    			return res;
			}else{
			 	return [];
			}
		},
		hasMore: true
	}
    getmintime(obj){
        if(!obj){return Date.now();}
        var objtype=Object.prototype.toString.call(obj);
        if(objtype=='[object Object]'){return obj.create_time;}
        if(objtype=='[object Array]'){return Math.min.apply(null,obj.map(o=>o.create_time));}
        return Date.now();
    }
    getmaxtime(obj){
        if(!obj){return Date.now();}
        var objtype=Object.prototype.toString.call(obj);
        if(objtype=='[object Object]'){return obj.create_time;}
        if(objtype=='[object Array]'){return Math.max.apply(null,obj.map(o=>o.create_time));}
        return Date.now();
    }
	beforeStorageMsg = {//本地存储之前数据
		get: async (e) => {
			let maxTime;
			let data = this.msgList
			if(data.length == 0 && e){
				data = e.data
			}
			if (data.length) {
				maxTime = this.getmintime( data );
			}else{
			    maxTime = Date.now()
			}
			console.log('beforeStorageMsg',maxTime);
			let res = await this.getCloudMsg({
				minTime: 0,
				maxTime
			})
			this.beforeStorageMsg.hasMore = res.data.length != 0
			return res
		},
		hasMore: true
	}
}
